<template>

  <div class="wrapper">
    <!-- header部分 -->
    <header style="height: 15vw;width: 100%">
      <p style="font-size: 6vw">用户登陆</p>
    </header>

    <!-- 表单部分 -->
    <div class="login-box" >
      <div style="padding: 0vw 3vw;margin-top: 24vw;border-radius: 5px;height: 20vw">
        <el-form ref="formRef" :rules="data.rules"  :model="data.form" style=" width: 100% ;height: 30vw;border-radius: 5px;" >
          <el-form-item prop="userId"  style="border-radius: 5px;margin-bottom: 5vw" size="large">
            <el-input  style="width: 100%; height: 12vw; font-size: 4vw;" v-model="data.form.userId" placeholder="请输入账号" prefix-icon="User"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input  show-password style="width: 100%; height: 12vw; font-size: 4vw;" v-model="data.form.password" placeholder="请输入密码" prefix-icon="Lock"></el-input>
          </el-form-item>
<!--  验证码-->
          <el-form-item prop="captcha" >
            <el-row>
              <el-col :span="12">
                <el-input style="width: 100%; height: 12vw; font-size: 4vw;" v-model="data.form.captcha" placeholder="请输入验证码" prefix-icon="Captcha"></el-input>
              </el-col>
              <el-col :span="8" :offset="1">
                <img :src="'data:image/png;base64,'+data.captchaImg" alt="captcha" class="w-100px h-30px" @click="loadCaptcha" style="width: 100%; height: 10vw; font-size: 3vw;"/>
              </el-col>
            </el-row>
          </el-form-item>

          <div  class="button-login" style="width: 100%; font-size: 4vw;">
            <el-button  @click="verifyCaptcha" >登陆</el-button>
          </div>
          <div  class="button-register" style="width: 100%; font-size: 4vw;">
            <el-button  @click="register" >去注册</el-button>
          </div>
        </el-form>
      </div>

    </div>

    <!-- 底部菜单部分 -->
    <Footer />
  </div>

</template>

<script setup lang="ts">

import {onMounted, reactive, ref} from 'vue';
import Footer from '../components/Footer.vue';
import { useRoute, useRouter } from 'vue-router';
import request from "@/utils/request";
import {ElMessage} from "element-plus";
import router from "@/router";
import { authService } from '@/service/AuthService';

const data = reactive({
  form:{
    userId: '',
    password: '',
    captcha: '' // 添加验证码字段
  },
  rules:{
    userId:[
      {required:true,message:'请输入账号',trigger:'blur'},
      {min: 1, max: 16, message: '账号长度应在 1 到 16 个字符之间', trigger: 'blur' }
    ],
    password:[
      {required:true,message:'请输入密码',trigger:'blur'},
      { min: 3, max: 8, message: '密码长度应在 3 到 8 个字符之间', trigger: 'blur'}
    ],
    captcha: [
      { required: true, message: '请输入验证码', trigger: 'blur' }
    ] // 添加验证码验证规则

  },
  captchaImg: '' // 验证码图片

})

onMounted(() => {
  localStorage.clear();
  authService.logout()
  loadCaptcha()
});


const formRef = ref()

// 加载验证码
const loadCaptcha = () => {
  request.get('/Captcha/getCaptcha').then(res => {
    if (res.code === 1) {
      data.captchaImg = res.data.imageBase64;
      data.form.captchaId = res.data.id; // 后端返回验证码ID
    } else {
      ElMessage.error(res.msg);
    }
  });
};

//验证验证码
const verifyCaptcha = () => {
  formRef.value.validate((valid)=>{
    if(valid){
      request.post('/Captcha/verifyCaptcha', {
        value: data.form.captcha,
        id: data.form.captchaId
      },{
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(res => {
        if (res.code === 1) {
          login();
        } else {
          ElMessage.error(res.msg);
          loadCaptcha(); // 重新加载验证码
        }
      });
    }
  })
};


const login =()=>{
  formRef.value.validate((valid)=>{
    if(valid){
      request.get('/User/getUserByIdByPass',{
        params:{
          userId:data.form.userId,
          password:data.form.password
        }
      }).then(res=>{
        if(res.code === 1){
          //登陆成功
          //存储后台返回的用户数据
          authService.login();
          localStorage.setItem("user",JSON.stringify(res.data.data)) //把json对象转换成json字符串存储
          localStorage.setItem("token",JSON.stringify(res.data.token)) //存储token
          localStorage.setItem("userId",JSON.stringify(res.data.data.userId))
          localStorage.setItem("userName",JSON.stringify(res.data.data.userName))
          localStorage.setItem("isLogged",JSON.stringify("true"))
          ElMessage.success("登陆成功")
          location.href = '/index'
        }else {
          loadCaptcha(); // 重新加载验证码
          ElMessage.error(res.msg)
        }
      })
    }
  })
}




const register = () => {
  router.push({ path: '/register'});
};

</script>

<style scoped>

/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}
/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #17BAF9;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}
/*表单部分 */

.button-login {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 0.1vw 0 0.1vw;
}
.button-login button {
  width: 100%;
  height: 12vw;
  font-size: 3.8vw;
  font-weight: 700;
  color: #fff;
  background-color: #38CA73;
  border-radius: 4px;
  border: none;
  outline: none;
}
.button-register {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 0.1vw 0 0.1vw;
}
.button-register button {
  width: 100%;
  height: 12vw;
  font-size: 3.8vw;
  font-weight: 700;
  /*与上面登陆按钮不同的只有颜色、背景色、边框不同*/
  color: #666;
  background-color: #EEE;
  border: solid 1px #DDD;
  border-radius: 4px;
  border: none;
  outline: none;
}
/****************** 底部菜单部分 ******************/
.wrapper .footer {
  width: 100%;
  height: 14vw;
  border-top: solid 1px #DDD;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.wrapper .footer li {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
  user-select: none;
  cursor: pointer;
}
.wrapper .footer li p {
  font-size: 2.8vw;
}
.wrapper .footer li i {
  font-size: 5vw;
}


.login-box{
  margin-top: 6vw;
  width: 100%;
  height: 30%;

}




</style>